﻿#include "cirt_lua.h"
#include "QString"
#include <QDebug>
#include "lua54/lua.hpp"




namespace CIRT {

DWORD WINAPI threadfunction(LPVOID lpp)//在线程中运行的函数，需要有一个WINAPI声明
{
    int i=0;
    while(true)
    {
        std::cout<<"thread running......"<<i<<std::endl;
    }
}
cirt_lua::cirt_lua()
{
    Lu = luaL_newstate();
    luaL_openlibs(Lu);
    luaopen_coroutine(Lu);
    DWORD threadid;
    //HANDLE hthread=CreateThread(NULL,0,threadfunction,0,CREATE_SUSPENDED,&threadid);//创建一条挂起的线程执行function

}

bool cirt_lua::parserProgram(string pro)
{
    int t = luaL_loadstring(Lu,pro.c_str());
    std::cout<<"parser program "<< t<<std::endl;
    if(t!=0)
    {
        PrintLuaError(Lu,t);
        return false;
    }
    return true;
}

void cirt_lua::runlua()
{

//    if(_mpro.isEmpty())  // || status != LUA_WAIT
//    {
//        QString str="Info: can not find a lua program for execute!";
//        emit sig_stringMsg(str);
//        qDebug()<<"can not find a lua program for execute!";
//        return;
//    }
//    load_string();
//    status=LUA_RUN;
//    if(lua_pcall(Lu,0,0,0)!=0)
//    {
//        QString str="Error: some error about lua program execute!"+QString::fromStdString(lua_tostring(Lu,-1));
//        emit sig_stringMsg(str);
//        qDebug()<<"Error: some error about lua program execute!"<<lua_tostring(Lu,-1);
//        lua_close(Lu);
//        return;
//    }

//    lua_getglobal(Lu,"main");
//    //lua_sethook(Lu,Lua_script::hook,LUA_HOOKLINE,0);
//    lua_pcall(Lu,0,0,0);
//    lua_close(Lu);
//    status=LUA_STOP;
    return;
}

void cirt_lua::PrintLuaError(lua_State *L, int sErr)
{
    if(sErr==0)
        return;
    const char* error;
    char sErrorType[256]={0};
    switch (sErr) {
    case LUA_ERRSYNTAX://编译时错误
        sprintf_s(sErrorType,sizeof(sErrorType),"%s","syntax error during pre-compilation");
        break;
    case LUA_ERRMEM://内存错误
        sprintf_s(sErrorType,sizeof(sErrorType),"%s","memory allocation error");
        break;
    case LUA_ERRRUN://运行错误
          sprintf_s(sErrorType,sizeof(sErrorType),"%s","runtime error");
        break;
    case LUA_YIELD://线程挂起
        sprintf_s(sErrorType,sizeof(sErrorType),"%s","Thread has Suspended");
        break;
    case LUA_ERRERR://错误处理时发生错误
         sprintf_s(sErrorType,sizeof(sErrorType),"%s","error while running the error handler function");
        break;
    default:
        break;
    }
    error= lua_tostring(L,-1);
    std::cout<<sErrorType<<" : "<<error<<std::endl;
    lua_pop(L,1);
}

}
